(function($) {

$.fn.multiselector = function(options) {    
    
    var self = this;
    
    this.element = $(this);
    this.container = $.create('div', {'class': 'multi-selector'}).insertBefore(this.element);
    
    settings = $.extend({ multiple: this.element.attr('multiple'),
                          debug: false }, options);
    
    this.element.children().each(function() {
        
        var child = $(this);
        var ungroupedList = null;
        
        if (child.is('optgroup')) {
            var container = $.create('div', {'class': 'multi-selector-optgroup'}).appendTo(self.container);
            var header = $.create('div', {'class': 'multi-selector-heading'}, child.attr('label')).appendTo(container);
            var list = $.create('ul', {'class': 'multi-selector-list'}).appendTo(container);
            
            header.click(function() {
                list.slideToggle();
                header.toggleClass('multi-selector-heading-closed');
            });
            
            child.children().each(function() {
                var child = $(this);
                
                var item = $.create('li', {'class': 'multi-selector-item'}, child.text()).appendTo(list);
                item.css('cursor','pointer');
                
                if (child.attr('selected')) {
                    item.addClass('multi-selector-selected');
                }
                
                item.click(function() {
                    child.attr('selected', !child.attr('selected'));
                    if (child.attr('selected')) {
                        item.addClass('multi-selector-selected');
                    } else {
                        item.removeClass('multi-selector-selected');
                    }
                });
            });
            
        } else if (child.is('option')) {
            if (ungroupedList === null) {
                ungroupedList = $.create('ul', {'class': 'multi-selector-list'}).appendTo(self.container);
            }
            
            var item = $.create('li', {'class': 'multi-selector-item'}, child.text()).appendTo(ungroupedList);
        }
    });
    
    this.element.hide();
};

}(jQuery));

/**
    <div>
        <div>
            <h1>Hest</h1>
            <ul>
                <li>Option</li>
                <li>Option</li>
            </ul>
            <ul>
                <li>Option</li>
                <li>Option</li>
                <li>Option</li>
            </ul>
        </div>
        <ul>
            <li>Option</li>
            <li>Option</li>
        </ul>
     <div>
*/